package com.woolink.per.common.util;

import java.sql.Date;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.woolink.per.common.Constants;
import com.woolink.per.common.QueryCondition;

/**
 * 
 * @author wuliquan
 * @version 2013-12-10
 * @see CommonUtil
 * @since
 */
public abstract class CommonUtil
{
    //成功
    private static final int SUCCESS = 0;
    
    /**
     * 
     * Description: 判断Map是否未空
     * Implement: <br>
     * @param map 需要检查的Map
     * @see
     * @return boolean 是否为空
     */
    @SuppressWarnings("rawtypes")
    public static boolean mapIsNull(Map map)
    {
        boolean isNull = true;
        
        if (null != map && !map.isEmpty())
        {
            isNull = false;
        }
        
        return isNull;
    }
    
    /**
     * 
     * Description: 判断结合死否为空，List Set适用
     * Implement: <br>
     * @param col 要检查的结合
     * @return
     * @see
     * @return boolean 是否为空
     */
    @SuppressWarnings("rawtypes")
    public static boolean collectionIsNull(Collection col)
    {
        boolean isNull = true;
        
        if (null != col && !col.isEmpty())
        {
            isNull = false;
        }
        
        return isNull;
    }
    
    /**
     * 
     * Description: 将Object类型的数组转成字符串
     * Implement: <br>
     * @param objs 对象数组
     * @see
     * @return String 转换后的字符串
     */
    public static String toString(Object[] objs)
    {
        if (null == objs)
        {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        for (int i = 0; i < objs.length; i++)
        {
            sb.append(objs[i]);
            if (i < objs.length - 1)
            {
                sb.append(Constants.Separator.SEPARATOR_COMMA);
            }
        }
        sb.append("]");
        return sb.toString();
    }
    
    /**
     * 检查数据库，如果违反唯一性约束，返回错误信息，否则返回成功
     * <功能详细描述>
     * @param resultCode 返回结果
     * @param passMessage 校验通过信息
     * @param errorMessage  错误信息
     * @return 页面提示信息
     * @see [类、类#方法、类#成员]
     */
    /**
     * 
     * Description: 检查数据库，如果违反唯一性约束，返回错误信息，否则返回成功
     * Implement: <br>
     * @param resultCode 返回结果
     * @param passMessage 校验通过信息
     * @param errorMessage  错误信息
     * @return
     * @see
     * @return String 页面提示信息
     * @author ozm2013-1-31下午2:55:16
     */
    public static String getExistCheckMessage(int resultCode,
            String passMessage, String errorMessage)
    {
        return (SUCCESS == resultCode) ? "{\"state\" : \"1\", \"message\" : \""
                + passMessage + "\"}" : "{\"state\" : \"0\", \"message\" : \""
                + errorMessage + "\"}";
    }
    
    /**
     * 判断查询条件是否存在
     * Description: <br>
     * Implement: <br>
     * @param queryConditon 查询条件
     * @see
     * @return boolean 查询条件是否存在
     */
    public static boolean conditionExist(QueryCondition queryConditon)
    {
        if (null == queryConditon || !stringExist(queryConditon.getKey())
                || !stringExist(queryConditon.getValue()))
        {
            return false;
        }
        return true;
    }
    
    /**
     * 判断字符串是否存在
     * Description: <br>
     * Implement: <br>
     * @param str 字符串
     * @see
     * @return boolean 是否存在
     * @author ozm2013-3-4上午9:44:18
     */
    public static boolean stringExist(String str)
    {
        if (null == str || "".equals(str.trim()))
        {
            return false;
        }
        return true;
    }
    
    /**
     * 将字符串转为字符数组
     * Description: <br>
     * Implement: <br>
     * @param str 原字符串
     * @param separator 分隔符
     * @return
     * @see
     * @return String[] 分割后字符数组
     * @author ozm2013-7-17下午4:44:51
     */
    public static String[] strToStrArray(String str, String separator)
    {
        String[] strArray = null;
        if (stringExist(str.trim()))
        {
            strArray = str.split(separator.trim());
        }
        
        return strArray;
    }
    
    /**
     * 创建复合条件查询
     * Description: <br>
     * Implement: <br>
     * @param queryCondition 查询条件实例
     * @return
     * @see
     * @return QueryCondition 构造完成的复合查询对象
     */
    public static QueryCondition createCompositeQueryCondition(
            QueryCondition queryCondition, List<String> conditionKeyList,
            List<String> conditionOperatorList, List<Object> conditionValueList)
    {
        queryCondition = queryCondition == null ? new QueryCondition()
                : queryCondition;
        if (!collectionIsNull(conditionKeyList))
        {
            queryCondition.setConditionKeyList(conditionKeyList);
        }
        
        if (!collectionIsNull(conditionOperatorList))
        {
            queryCondition.setConditionOperatorList(conditionOperatorList);
        }
        
        if (!collectionIsNull(conditionValueList))
        {
            queryCondition.setConditionValueList(conditionValueList);
        }
        
        return queryCondition;
        
    }
    
    /**
     * 获取当前时间
     * Description: <br>
     * Implement: <br>
     * @return
     * @see
     * @return Timestamp
     * @author ozm2013-3-15上午10:34:42
     */
    public static Timestamp getCurrentTime()
    {
        return new Timestamp(System.currentTimeMillis());
    }
    
    /**
     * 将时间字符串转为timestamp类型
     * Description: <br>
     * Implement: <br>
     * @param timeStr 时间字符串
     * @param format 格式
     * @return
     * @throws ParseException
     * @see
     * @return Timestamp 返回对象
     * @author ozm2013-7-17下午2:55:12
     */
    public static Timestamp strToTimestamp(String timeStr)
            throws ParseException
    {
        Timestamp ts = Timestamp.valueOf(timeStr);
        return ts;
    }
    
    /**
     * 将日期字符串转为date类型
     * Description: <br>
     * Implement: <br>
     * @param dateStr
     * @param format
     * @return
     * @throws ParseException
     * @see
     * @return Date
     * @author ozm2013-7-17下午3:18:40
     */
    public static java.sql.Date strToDate(String dateStr) throws ParseException
    {
        java.sql.Date date = Date.valueOf(dateStr);
        return date;
    }
    
    /**
     * 
     * Description: 将日期字符串转化为java.util.Date类型<br>
     * Implement: <br>
     * @param dateStr
     * @return
     * @throws ParseException
     * @see
     * @return java.util.Date
     * @author lizl 2013年7月22日10:53:58
     */
    public static java.util.Date strToUtilDate(String dateStr)throws ParseException
    {
        SimpleDateFormat sft = new SimpleDateFormat("yyyy-MM-dd");
        java.util.Date date = sft.parse(dateStr);
        return date;
    }
    
    /**
     * 返回时间字符串
     * Description: <br>
     * Implement: <br>
     * @param time 时间
     * @param format 输出格式
     * @return
     * @see
     * @return String
     * @author ozm2013-4-2下午2:05:34
     */
    public static String timeToString(Timestamp time, String format)
    {
        if (null == format)
        {
            //默认输出格式
            format = "yyyy-MM-dd HH:mm:ss";
        }
        
        if (null == time)
        {
            //默认使用系统时间
            time = getCurrentTime();
        }
        
        SimpleDateFormat dateFormat = new SimpleDateFormat(format);// 设定格式
        
        return dateFormat.format(time);
    }
    
    /**
     * 
     * Description: <br>当前时间增加20年
     * Implement: <br>
     * @return
     * @see
     * @return Date
     * @author zouqf
     */
    public static java.util.Date getValidTime()
    {
        java.util.Date date = new java.util.Date();
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(Calendar.YEAR, 20);//此处修改年限
        return c.getTime();
    }
    
    /**
     * 补全SQL中的And
     * Description: <br>
     * Implement: <br>
     * @param sql 待处理的SQL
     * @param hasPreCondition 之前是否已经添加条件
     * @return
     * @see
     * @return String  处理完成的SQL字符串
     * @author ozm2013-3-26下午2:22:42
     */
    public static String makeSQL(String sql, boolean hasPreCondition)
    {
        if (hasPreCondition)
        {
            sql = sql + " and ";
            
        }
        
        return sql;
    }
    
    /**
     * 通过对象获取XMl串
     * Description: <br>
     * Implement: <br>
     * @param name 根节点名
     * @param className 对象类型
     * @param obj 对象
     * @return
     * @see
     * @return String xml字符串
     * @author ozm2013-7-11下午5:35:01
     */
    public static String getXmlStrFromObjec(String name, Class className,
            Object obj)
    {
        XStream xstream = new XStream(new DomDriver("UTF-8"));
        xstream.alias(name, className);
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
                + xstream.toXML(obj);
        return xml;
    }
    
    /**
     * 通过xml字符串获取应答对象
     * Description: <br>
     * Implement: <br>
     * @param name 根节点名
     * @param className 对象类型
     * @param xmlStr xml消息串
     * @return
     * @see
     * @return Response 应答对象
     * @author ozm2013-7-16下午5:39:24
     */
    
    //    /**
    //     * 通过输入流获取ObjectInputStream对象
    //     * Description: <br>
    //     * Implement: <br>
    //     * @param inputStream 输入流
    //     * @param charsetName 字符集
    //     * @return
    //     * @see
    //     * @return ObjectInputStream 
    //     * @author ozm2013-7-13上午10:32:49
    //     * @throws IOException 
    //     */
    //    public static ObjectInputStream getOISFromInputStream(InputStream inputStream, String charsetName) throws IOException
    //    {
    //        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,charsetName));
    ////      String line="";
    ////      StringBuffer buffer = new StringBuffer(1024);
    ////      while((line = br.readLine()) != null)
    ////      {
    ////            buffer.append(line);
    ////       }
    //        XStream xstream = new XStream(new DomDriver(charsetName));
    //        xstream.alias("request", Request.class);
    ////        xstream.alias("header", Header.class);
    //        xstream.alias("body", Body.class);
    //        xstream.alias("order", Order.class);
    //        ObjectInputStream in =  xstream.createObjectInputStream(br);   
    //        return in;
    //     
    //    }
    
    

    //    public static  String getMD5Ciphertext(String plaintextStr)
    //    {
    //        Md5PasswordEncoder md5 = new Md5PasswordEncoder();
    //        
    //        String md5Password=md5.encodePassword("plaintextStr", null);
    //        
    //        
    //        System.out.println(md5Password);
    //        return md5Password;
    //    }

    
    /**
     * MD5加密和C#匹配
     * Description: <br>
     * Implement: <br>
     * @param str
     * @return
     * @see
     * @return String
     * @author ozm2013-7-15上午10:59:47
     */
    public static String getMd5String(String str)
    {
        return DigestUtils.md5Hex(str).toUpperCase();
    }
    
    /**
     * 错误码、订单状态映射关系
     * Description: <br>
     * Implement: <br>
     * @param code
     * @return
     * @see
     * @return Object
     * @author wootide-0005
     */
    public static Object getCodeMsg(Integer code)
    {
        Map<Object, Object> codeMsg = new HashMap<Object, Object>();
        codeMsg.put(1, "执行成功");
        codeMsg.put(100, "参数错误");
        codeMsg.put(101, "缺少参数");
        codeMsg.put(102, "参数类型错误");
        codeMsg.put(103, "参数值错误");
        codeMsg.put(104, "方法名不存在");
        codeMsg.put(200, "数据错误");
        codeMsg.put(201, "查询失败");
        codeMsg.put(202, "新增失败");
        codeMsg.put(203, "更新失败");
        codeMsg.put(204, "删除失败");
        codeMsg.put(300, "账号不存在或签名错误");
        codeMsg.put(400, "未知错误");
        codeMsg.put(500, "二维码发送失败或者重发次数已经超出限定");
        //codeMsg.put("N", 0);
        //codeMsg.put("P", 1);
        //codeMsg.put("C", 2);
        //codeMsg.put("E", 3);
        
        return (Object)codeMsg.get(code);
    }
    public static Object getCodeMsg(String code){
        Map<Object, Object> codeMsg = new HashMap<Object, Object>();
        codeMsg.put("N", 1);
        codeMsg.put("P", 2);
        codeMsg.put("C", 4);
        codeMsg.put("E", 0);
        return (Object)codeMsg.get(code);
    }
    /**
     * 返回分销商错误码映射关系
     * Description: <br>
     * Implement: <br>
     * @param code
     * @return
     * @see
     * @return Object
     * @author wootide-0005
     */
    public static Object getDistrictCode(Integer code)
    {
        Map<Object, Object> codeMsg = new HashMap<Object, Object>();
        codeMsg.put(0, "操作成功");
        codeMsg.put(100, "用户不存在或签名错误");
        codeMsg.put(101, "服务不存在");
        codeMsg.put(102, "消息体错误");
        codeMsg.put(103, "数据格式错误");
        codeMsg.put(201, "新增订单已存在");
        codeMsg.put(202, "修改订单不存在");
        codeMsg.put(203, "取消订单不存在");
        
        return (Object)codeMsg.get(code);
    }
    
    public static void main(String args[])
    {
         System.out.println(getMd5String("123456"));
        
        //System.out.println(getMd5String("4766322f-d0ac-4c1f-8fb3-f7e59e9cc45b7c75595ed735cecfb211e38ad6237ef42013-07-17 11:46:13"));
        //        try
        //        {
        //            String str_test ="2011-04-24";
        ////            System.out.println(strToTimestamp(str_test));
        ////            Date date = new SimpleDateFormat("yyyy-MM-dd").parse(str_test);
        //            System.out.println(strToDate(str_test));
        //            
        //            
        //        }
        //        catch (ParseException e)
        //        {
        //            
        //            e.printStackTrace();
        //        }
        //System.out.println(CommonUtil.strToStrArray("11|22|33", "").toString());
    }
    //    
    //    public static String MD5(String str)  
    //    {  
    //        byte[] result = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(Encoding.UTF8.GetBytes(str));  
    //        StringBuilder output = new StringBuilder(16);  
    //        for (int i = 0; i < result.Length; i++)  
    //        {  
    //            // convert from hexa-decimal to character  
    //            output.Append((result[i]).ToString("x2", System.Globalization.CultureInfo.InvariantCulture));  
    //        }  
    //        return output.ToString();  
    //    }  
}
